<template>
  <breadCrumb ref="breadcrumb" :item="item"></breadCrumb>
  <!-- 顶部 -->
  <div class="table-wrapped">
    <!-- 表格顶部 -->
    <div class="table-header">
      <!-- 搜索 -->
      <div class="left-wrapped">
        <div class="search-wrapped">
          <!-- 账号搜索框 -->
          <el-input v-model="adminAccount" class="w-50 m-2" size="large" placeholder="输入账号进行搜索" :prefix-icon="Search"
            @change="goSearch(adminAccount)" />
        </div>
        <div class="select-wrapped">
          <!-- 搜索部门下拉框 -->
          <el-select v-model="adminDepartment" placeholder="请选择部门" @change="goSearchbyDepartment(adminDepartment)"
            clearable @clear="clearOperation">
            <el-option v-for="(item, index) in departmentList" :key="index" :label="item"
              :value="item" />
          </el-select>
        </div>
      </div>

      <!-- 筛选用户 -->
      <div class="button-wrapped">
        <el-button plain type="primary" @click="goShowFrozen">筛选冻结用户</el-button>
        <el-button plain type="primary" @click="getAdminList">显示全部用户</el-button>
      </div>
    </div>
    <el-scrollbar max-height="650px">
    <!-- 表格内容 -->
    <div class="table-content">
      <el-table :data="tableData" style="width: 100%" border stripe @row-dblclick="showUserInfo">
        <el-table-column type="index" width="50" :index="indexMethod" />
        <el-table-column prop="account" label="账号" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="sex" label="性别" />
        <el-table-column prop="department" label="部门" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <div>
              <el-tag type="primary" class="ml-2" v-if="row.status === 1">冻结</el-tag>
              <el-tag type="success" class="ml-2" v-else>正常</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间">
          <template #default="{ row }">
            <div>{{ row.create_time?.slice(0, 10) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="update_time" label="更新时间">
          <template #default="{ row }">
            <div>{{ row.update_time?.slice(0, 10) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <div>
              <el-button type="success" @click="goFreeze(row.id)" :disabled='row.status == 1'>冻结</el-button>
              <el-button type="danger" @click="goUnFreeze(row.id)" :disabled='row.status == 0'>解冻</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-scrollbar>
    <!-- 底部分页 -->
    <div class="table-footer">
      <el-pagination size="small" background layout="prev, pager, next" :total="totalData"
        :page-size="paginationData.pageSize" 
        :current-page="paginationData.currentPage" @current-change="goChangePage" :hide-on-single-page="value" />
    </div>
  </div>
  <userInfo ref="userInfoRef"></userInfo>
</template>

<script lang="ts" setup>
import { ref, reactive, provide } from "vue"
import breadCrumb from "../../../components/breadCrumb.vue"
import { Search } from '@element-plus/icons-vue'
import { getAdminListAPI, searchUserByAccountAPI, getUserListByDepartmenAPI, freezeUserAPI, unfreezeUserAPI, getFreezeUserListAPI,  getUserListByPagerAPI, getUserCountByIdentityAPI } from '../../../api/userinfo'
import { debounce } from 'lodash'
import userInfo from "../components/user_info.vue"
import { tracking } from '../../../utils/operate.js'
import { getCompanyDepartment } from '../../../api/setting'

const breadcrumb = ref()
const item = ref({
  first: '用户管理',
  second: '用户列表'
})

const value = ref(false)

const adminAccount = ref('')
const adminDepartment = ref()

interface User {
  status: number

}

const tableData = ref<User[]>([])


const title = '用户'


// 分页数据
const paginationData = reactive({
  currentPage: 1,
  pageSize: 5
})

const totalData = ref()

// 获取管理员总数
const getAdminCount = async () => {
  const res = await getUserCountByIdentityAPI(title)
  totalData.value = res.data.data
}
getAdminCount()

// 获取第一页数据
const getFirstPage = async () => {
  paginationData.currentPage = 1
  const res = await getUserListByPagerAPI({ identity: title, pager: 1 })
  tableData.value = res.data.data
  getAdminCount()
}


// 换页
const goChangePage = async (page) => {
  paginationData.currentPage = page
  const res = await getUserListByPagerAPI({ identity: title, pager: paginationData.currentPage })
  tableData.value = res.data.data
}

// 表的索引
const indexMethod = (index) => {
  return index + (paginationData.currentPage - 1) * 5 + 1
}

// 获取管理员列表
const getAdminList = async () => {
  const res = await getAdminListAPI(title)
  tableData.value = res.data.data
  paginationData.currentPage = 1
  totalData.value = tableData.value.length
  paginationData.pageSize = tableData.value.length
}


// 部门列表
const departmentList = ref()

const getDepartmentList = async () => {
  const res = await getCompanyDepartment()
  departmentList.value = Array.from(JSON.parse(res.data.data))
}
getDepartmentList()


// 根据账号搜索用户 --- 表单输入 利用 debounce 防抖
const goSearch = debounce(async (adminAccount) => {
  const res = await searchUserByAccountAPI({ account: adminAccount, identity: title })
  tableData.value = res.data.data
  if (adminAccount === '') {
    getFirstPage()
  }
}, 500)

// 根据账部门索用户 --- 表单输入 利用 debounce 防抖
const goSearchbyDepartment = async (department) => {
  const res = await getUserListByDepartmenAPI(department)

  tableData.value = res.data.data
  paginationData.currentPage = 1
  totalData.value = tableData.value.length
  paginationData.pageSize = tableData.value.length
}

// 冻结用户
const goFreeze = async (id) => {
  await freezeUserAPI(1, id)
  tracking("用户管理", `冻结`, id , "高级")
  if (tableData.value.length !== 1) {
    goChangePage(paginationData.currentPage)
  } else {
    tableData.value[0].status = 1
  }
}

// 解冻用户
const goUnFreeze = async (id) => {
  await unfreezeUserAPI(0, id)
  tracking("用户管理", `解冻`, id , "高级")
  if (tableData.value.length !== 1) {
    goChangePage(paginationData.currentPage)
  } else {
    tableData.value[0].status = 0
  }
}

// 清空操作
const clearOperation = () => {
  getFirstPage()
  adminDepartment.value = ''
}

// 获取所有冻结用户
const goShowFrozen = async () => {
  const res = await getFreezeUserListAPI()
  tableData.value = res.data.data
  paginationData.currentPage = 1
  totalData.value = tableData.value.length
  paginationData.pageSize = tableData.value.length
}

getFirstPage()

const userInfoRef = ref()
const showUserInfo = (row) => {
  userInfoRef.value.openDialog(row)
}

// 提供方法给后代组件
provide('getFirstPage', getFirstPage)
</script>

<style lang="scss" scoped>
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 18px 0 10px 0;

  .left-wrapped {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .search-wrapped {
      display: flex;
      align-items: center;
      margin-right: 20px;
    }

    .select-wrapped {
      width: 246px;
      display: flex;
      align-items: center;
      align-self: center;
      margin-right: 20px;
    }
  }

  .button-wrapped {
    margin-bottom: 20px;
  }

}

.table-footer {
  margin-top: 30px;
}

:deep(.el-select__wrapper) {
  padding: 13px 12px;
}

:deep(.button-wrapped .el-button) {
  height: 40px;
  width: 200px;
}

:deep(.search-wrapped .el-input) {
  width: 246px;
}

:deep(.el-table--enable-row-transition .el-table__body td.el-table__cell) {
  transition: none;
}
</style>